import 'package:flutter/material.dart';
// viewInsets.bottom 就是键盘的高度
typedef ChangeMetricsCallback = void Function(EdgeInsets viewInsets);

class ChangeMetricsWidget extends StatefulWidget {
  final Widget child;
  final ChangeMetricsCallback? callback;

  const ChangeMetricsWidget({Key? key, required this.child, this.callback})
      : super(key: key);

  @override
  State<ChangeMetricsWidget> createState() => _ChangeMetricsWidgetState();
}

class _ChangeMetricsWidgetState extends State<ChangeMetricsWidget>
    with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance.addPostFrameCallback((time) {
      if (widget.callback != null) {
        widget.callback!(MediaQuery.of(context).viewInsets);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}
